package des;

import java.io.*;
import java.security.Key;
import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.SecretKeySpec;

public class DesEncryptDecrypt {
	public static void encode(byte[] bytes, OutputStream out, String pass)
			throws Exception {
		System.out.println("DES mit pW: " + pass);
		Cipher c = Cipher.getInstance("DES");
		Key k = new SecretKeySpec(pass.getBytes(), "DES");
		c.init(Cipher.ENCRYPT_MODE, k);

		OutputStream cos = new CipherOutputStream(out, c);
		cos.write(bytes);
		cos.flush();

	}

	public static byte[] encode(byte[] bytes, String pass) throws Exception {
		Cipher cipher = Cipher.getInstance("DES");
		Key k = new SecretKeySpec(pass.getBytes(), "DES");
		cipher.init(Cipher.ENCRYPT_MODE, k);
		return cipher.doFinal(bytes);

	}

	public static byte[] decode(byte[] bytes, String pass) throws Exception {
		Cipher cipher = Cipher.getInstance("DES");
		Key k = new SecretKeySpec(pass.getBytes(), "DES");
		cipher.init(Cipher.DECRYPT_MODE, k);
		return cipher.doFinal(bytes);

	}

	public static byte[] decode(InputStream is, String pass) throws Exception {
		Cipher c = Cipher.getInstance("DES");
		Key k = new SecretKeySpec(pass.getBytes(), "DES");
		c.init(Cipher.DECRYPT_MODE, k);

		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		CipherInputStream cis = new CipherInputStream(is, c);

		for (int b; (b = cis.read()) != -1;)
			bos.write(b);

		return bos.toByteArray();
	}

	public static byte[] decode(byte[]  in, int length, String pw) throws Exception {
		byte[] raw = new byte[length];
		for (int i = 0; i < length; i++) {
			raw[i] = in[i];
		}
		return decode(raw, pw);
	}

}